package com.ljw.hmall.interceptor;

import com.ljw.hmall.pojo.NonWebRequestAttributes;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MyFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        if (attributes!=null){
            if (attributes instanceof ServletRequestAttributes){
                HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
                String authorization = request.getHeader("authorization");
                System.out.println("feign的拦截器获取到网关中设置的请求头是："+authorization);
                requestTemplate.header("authorization",authorization);

            }else if (attributes instanceof NonWebRequestAttributes){
                String authorization = (String) attributes.getAttribute("authorization", 0);
                requestTemplate.header("authorization",authorization);
            }

        }

    }
}
